package com.white.camlib;

import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Build;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

/**
 * @author ytf
 * Created by on 2021/06/04 10:12
 */
public class PreviewHideWindow {

    private WindowManager windowManager;
    private WindowManager.LayoutParams params;


    public PreviewHideWindow(Context mContext) {
        windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        onCreate();
    }

    private void onCreate(){
        params = new WindowManager.LayoutParams(1, 1,
                WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                PixelFormat.TRANSPARENT);

        params = new WindowManager.LayoutParams();
        params.width = 16;
        params.height = 9;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        }else {
            params.type =  WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }
        params.format = PixelFormat.TRANSLUCENT;
        //可使用FLAG_DISMISS_KEYGUARD选项直接解除非加锁的锁屏状态。此选项只用于最顶层的全屏幕窗口。
        params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL //不耽误其他事件
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;

        params.gravity = Gravity.TOP | Gravity.START;
        params.alpha = PixelFormat.TRANSPARENT;

        params.x = params.y = 1;
    }

    private void removeParent(View v){
        if(v != null && v.getParent() != null){
            ViewGroup p = (ViewGroup) v.getParent();
            p.removeView(v);
        }
    }

    private View currentView;
    private boolean hasAttached;

    public void attach(View v){
        currentView = v;
        windowManager.addView(currentView, params);
        hasAttached = true;
    }

    public void detach(){
        if(hasAttached && currentView != null && currentView.getParent() != null){
            windowManager.removeView(currentView);
            hasAttached = false;
        }
    }
}
